// import React from 'react'
import Breadcrumb from '../../components/breadcrumb/Bread'
import { Col, Row } from 'antd';
import { Button, Form, Input, Select } from 'antd';
import { DatePicker, Space, Menu } from 'antd'
import { DownloadOutlined } from '@ant-design/icons';
import { Radio } from 'antd';
import React, { useState } from 'react';
import '../../assets/styles/center.css'
import { DownOutlined, UpOutlined, SettingOutlined, EyeOutlined,CrownOutlined ,BookOutlined,ClockCircleOutlined,TrophyOutlined} from '@ant-design/icons';
import { Dropdown, message, Tooltip } from 'antd';
import { Divider } from 'antd';
import { Table } from 'antd';
import { useEffect } from 'react';
import api from '../../aips/role'
import { Pagination } from 'antd';
import { Drawer } from 'antd';
import { Tree } from 'antd';
import { useRef } from 'react';
import filterMenu from '../../utils/pathMenu'
const { TextArea } = Input;


const showTotal = (total) => `Total ${total} items`;
const { Option } = Select;
const layout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 16,
  },
};
const tailLayout = {
  wrapperCol: {
    offset: 6,
    span: 16,
  },
};


const handleMenuClick = (e) => {
  // 重置密码
  message.info('Click on menu item.');
  console.log('click', e);
};
const items = [
  {
    label: '导出Excel',
    key: '1',
  },
];
const menuProps = {
  items,
  onClick: handleMenuClick,
};

const rowSelection = {
  onChange: (selectedRowKeys, selectedRows) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
  },
  getCheckboxProps: (record) => ({
    disabled: record.name === 'Disabled User',
    // Column configuration not to be checked
    name: record.name,
  }),
};
const Role = () => {
  const [selectionType, setSelectionType] = useState('checkbox');
  const [size, setSize] = useState('large');
  const [form] = Form.useForm();

  const onFinish = (values) => {
    console.log(values);
  };
  const onReset = () => {
    form.resetFields();
  };

  const { RangePicker } = DatePicker;
  const [data, setData] = useState([])
  useEffect(() => {
    addRole()
  }, [])

  function addRole() {
    api.role().then(res => {
      console.log(res);
      setData(res.rows)
    })
  }


  const [open, setOpen] = useState(false);
  const showDrawer = () => {
    setOpen(true);

  };
  const onClose = () => {
    setOpen(false);
  };

  const columns = [
    {
      title: '角色',
      dataIndex: 'roleName',
    },
    {
      title: '描述',
      dataIndex: 'remark',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      sorter: {
        compare: (a, b) => a.chinese - b.chinese,
        multiple: 3,
      },
    },
    {
      title: '修改时间',
      dataIndex: 'modifyTime',
      sorter: {
        compare: (a, b) => a.math - b.math,
        multiple: 2,
      },
    },
    {
      title: '操作',
      dataIndex: 'english',
      render: (_, record) => <i><SettingOutlined style={{ color: '#1189FE' }} onClick={() =>
        adduser(record)
      }
      /><EyeOutlined style={{ color: 'rgb(66, 185, 131)', marginLeft: '20px' }} onClick={() =>
        nextArr(record)}
        /></i>
    },
  ];

  const formRef = useRef()
  const [treeData, setTreeData] = useState([])
  const [yesArr, setYesArr] = useState([])
  //修改
  async function adduser(e) {
    //获取角色对应菜单
    // console.log(e);
    const res = await api.menu()
    // console.log(res);
    setTreeData(filterMenu(res.rows.children))
    // console.log(treeData);
    const re = await api.roleMenu(e.roleId)
    console.log(re);
    setYesArr(re)
    showDrawer()
    form1.setFieldsValue({
      roleName: e.roleName,
      remark: e.remark,
      roleId: e.roleId
    })
  }


const [roleNext,setRoleNext]=useState({})
const [nestArr,setNestArr]=useState({})
 async function nextArr(e) {
    console.log(e);
    setRoleNext(e)
    const res = await api.menu()
    // console.log(res);
    setTreeData(filterMenu(res.rows.children))
    const re = await api.roleMenu(e.roleId)
    console.log(re);
    setNestArr(re)


    showDrawerone()
  }
  //新增
  async function addrole() {
    const res = await api.menu()
    // console.log(res);
    setTreeData(filterMenu(res.rows.children))
    showDefaultDrawer()
  }

  const onChange = (pagination, filters, sorter, extra) => {
    console.log('params', pagination, filters, sorter, extra);
  };
  function showSizeChanger() {

  }
  function showQuickJumper() { }

  const [form1] = Form.useForm();
  const onGenderChange = (value) => {
    switch (value) {
      case 'male':
        form.setFieldsValue({
          note: 'Hi, man!',
        });
        return;
      case 'female':
        form.setFieldsValue({
          note: 'Hi, lady!',
        });
        return;
      case 'other':
        form.setFieldsValue({
          note: 'Hi there!',
        });
    }
  };




  // const App = () => {
    // 角色信息
    const [openone, setOpenone] = useState(false);
    const showDrawerone = () => {
      setOpenone(true);
    };
    const onCloseone = () => {
      setOpenone(false);
    };
  const onFinish1 = (values) => {
    console.log(values);
    const menuId = checkedKeys.checked.join()
    //  console.log(m);
    console.log(menuId);
    //修改提交
    api.modifRole({ ...values, menuId }).then(res => {
      onClose()
      message.success('修改成功')
    })

  };
  const onReset1 = () => {
    form.resetFields();
  };
  const onFill = () => {
    form.setFieldsValue({
      note: 'Hello world!',
      gender: 'male',
    });
  };

  // const treeData = [
  //   {
  //     title: '系统管理',
  //     key: '0-0',
  //     children: [
  //       {
  //         title: '用户管理',
  //         key: '0-0-0',
  //         children: [
  //           {
  //             title: '新增用户',
  //             key: '0-0-0-0',
  //           },
  //           {
  //             title: '修改用户',
  //             key: '0-0-0-1',
  //           },
  //           {
  //             title: '删除用户',
  //             key: '0-0-0-2',
  //           },
  //           {
  //             title: '导出Excel',
  //             key: '0-0-0-3',
  //           },
  //           {
  //             title: '密码重置',
  //             key: '0-0-0-4',
  //           },
  //         ],
  //       },
  //       {
  //         title: '角色管理',
  //         key: '0-0-1',
  //         children: [
  //           {
  //             title: '新增角色',
  //             key: '0-0-1-0',
  //           },
  //           {
  //             title: '修改角色',
  //             key: '0-0-1-1',
  //           },
  //           {
  //             title: '删除角色',
  //             key: '0-0-1-2',
  //           },
  //           {
  //             title: '导出Excel',
  //             key: '0-0-1-4',
  //           },
  //         ],
  //       },
  //       {
  //         title: '菜单管理',
  //         key: '0-0-2',
  //         children: [
  //           {
  //             title: '新增菜单',
  //             key: '0-0-2-0',
  //           },
  //           {
  //             title: '修改菜单',
  //             key: '0-0-2-1',
  //           },
  //           {
  //             title: '删除菜单',
  //             key: '0-0-2-2',
  //           },
  //           {
  //             title: '导出Excel',
  //             key: '0-0-2-4',
  //           },
  //         ],
  //       },
  //     ],
  //   },
  //   {
  //     title: '系统监控',
  //     key: '0-1',
  //     children: [
  //       {
  //         title: '0-1-0-0',
  //         key: '0-1-0-0',
  //       },
  //       {
  //         title: '0-1-0-1',
  //         key: '0-1-0-1',
  //       },
  //       {
  //         title: '0-1-0-2',
  //         key: '0-1-0-2',
  //       },
  //     ],
  //   },
  //   {
  //     title: '0-2',
  //     key: '0-2',
  //   },
  // ];

  const [expandedKeys, setExpandedKeys] = useState(['0-0-0', '0-0-1']);
  const [checkedKeys, setCheckedKeys] = useState(['0-0-0']);
  const [selectedKeys, setSelectedKeys] = useState([]);
  const [autoExpandParent, setAutoExpandParent] = useState(true);
  const onExpand = (expandedKeysValue) => {
    console.log('onExpand', expandedKeysValue);
    // if not set autoExpandParent to false, if children expanded, parent can not collapse.
    // or, you can remove all expanded children keys.
    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(false);
  };
  const onCheck = (checkedKeysValue, e) => {

    console.log('onCheck', checkedKeysValue, e);
    setCheckedKeys(checkedKeysValue);
    setYesArr(checkedKeysValue)
  };
  const onSelect = (selectedKeysValue, info) => {
    console.log('onSelect', info);
    setSelectedKeys(selectedKeysValue);
  };

  const menu = (
    <Menu
      items={[
        {
          key: '1',
          label: '展开所有',
          onClick: handleMenuClicks,
        },
        {
          key: '2',
          label: '合并所有',
          onClick: handleMenuClicks,
        },
        {
          key: '3',
          label: '父子关联',
          onClick: handleMenuClicks,
        },
        {
          key: '4',
          onClick: handleMenuClicks,
          label: '取消关联',
        },
      ]}
    />
  );
  let aus = false
  function handleMenuClicks(e) {
    if (e.key == '1') {
      console.log(1);

      aus = true
      console.log(aus);
    } else if (e.key == '2') {
      console.log(2);
    } else if (e.key == '3') {
      console.log(3);
    } else if (e.key == '4') {
      console.log(4);
    }
  }


  // 新增
  const [opent, setOpent] = useState(false);
  // const [sizet, setSizet] = useState();
  const showDefaultDrawer = () => {
    // setSize('default');
    setOpent(true);
  };
  const showLargeDrawer = () => {
    // setSize('large');
    setOpen(true);
  };
  const onCloset = () => {
    setOpent(false);
  };
  const onFinish2 = (values) => {
    console.log(values, checkedKeys);
    const menuId = checkedKeys.checked.join()
    values = {
      ...values,
      menuId: menuId
    }
    api.addrole({ ...values }).then(res => {
      addRole()
      onClose()
      message.success('新增成功')
    })
    //新增角色接口


  };
  const onChecks = (checkedKeysValue, e) => {

    console.log('onCheck', checkedKeysValue, e);
    setCheckedKeys(checkedKeysValue);
    setYesArr(checkedKeysValue)
  };
  const onSelects = (selectedKeysValue, info) => {
    console.log('onSelect', info);
    setSelectedKeys(selectedKeysValue);
  };


  return (
    <div>
      <div style={{ margin: '5px 0px 30px 0px' }}>

        <Breadcrumb ></Breadcrumb>
      </div>
      <Form {...layout} form={form} name="control-hooks" onFinish={onFinish}>
        <Row>
          <Col span={9}>
            <Form.Item
              name="name"
              label="角色"
            >
              <Input style={{ width: '280px', height: '32px' }} />
            </Form.Item>
          </Col>
          <Col span={9}>
            <Form.Item
              name="note"
              label="创建时间"
            >
              <RangePicker size='' style={{ width: '280px', height: '34px' }} />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item {...tailLayout}>
              <Button type="primary" htmlType="submit" style={{ marginRight: '10px' }}>
                确认
              </Button>
              <Button htmlType="button" onClick={onReset}>
                重置
              </Button>
            </Form.Item>
          </Col>
        </Row>



      </Form>
      <div >
        <Radio.Group value={size} onChange={(e) => setSize(e.target.value)} className='fcc' style={{ width: '260px' }}>
          <Radio.Button value="large" onClick={addrole}>新增</Radio.Button>
          <Radio.Button value="default">删除</Radio.Button>
          <Dropdown menu={menuProps}>
            <Button>
              <Space>
                更多操作
                <DownOutlined />
              </Space>
            </Button>
          </Dropdown>
        </Radio.Group>
      </div>


      <Divider />
      <Table
        rowSelection={{
          type: selectionType,
          ...rowSelection,
        }}
        columns={columns} dataSource={data} onChange={onChange} rowKey='roleId'
        pagination={{
          total: 50, showSizeChanger, showQuickJumper
        }}
      />
      <>

        <Drawer title="修改角色" placement="right" onClose={onClose} open={open} width={500}
          footer footerStyle={{ height: 60 }}>
          <Form {...layout} form={form1} name="control-hooks" onFinish={onFinish1} ref={formRef}>
            <Form.Item
              name="roleName"
              label="角色名称："

            >
              <Input />
            </Form.Item>
            <Form.Item
              name="remark"
              label="角色描述："
            >
              <TextArea rows={4} />
            </Form.Item>
            <Form.Item
              name="roleId"
              label="权限选择："
            >
              <Tree
                checkable
                checkStrictly
                checkedKeys={yesArr}
                onSelect={onSelect}
                onCheck={onCheck}
                treeData={treeData}
                defaultExpandAll={aus}

              />
            </Form.Item>
            <div style={{ bottom: '0', height: '60px', zIndex: 1000, position: 'absolute', width: '450px', display: 'flex', alignItems: 'center' }} >
              <Dropdown overlay={menu}>
                <a onClick={(e) => e.preventDefault()}>
                  <Button>
                    <Space>
                      树操作
                      <UpOutlined />
                    </Space>
                  </Button>
                </a>
              </Dropdown>
              <Button htmlType="button" onClick={onReset1} style={{ marginRight: '10px', marginLeft: '220px' }}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
            </div>
          </Form>
        </Drawer>
      </>
      <>

        <Drawer
          title='新增角色'
          placement="right"
          size={size}
          onClose={onCloset}
          open={opent}
          width='500'
          footer
          destroyOnClose
          footerStyle={{ height: 60 }}

        >
          <Form {...layout} name="control-hooks" onFinish={onFinish2} >
            <Form.Item
              name="roleName"
              label="角色名称："
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="remark"
              label="角色描述："
            >
              <TextArea rows={4} />
            </Form.Item>
            <Form.Item
              name="roleId"
              label="权限选择："
            >
              <Tree
                checkable
                checkStrictly
                defaultExpandedKeys={[]}
                defaultSelectedKeys={[]}
                defaultCheckedKeys={[]}
                onSelect={onSelects}
                onCheck={onChecks}
                treeData={treeData}
                defaultExpandAll={aus}

              />
            </Form.Item>
            <div style={{ bottom: '0', height: '60px', zIndex: 1000, position: 'absolute', width: '450px', display: 'flex', alignItems: 'center' }} >

              <Dropdown overlay={menu}>
                <a onClick={(e) => e.preventDefault()}>
                  <Button>
                    <Space>
                      树操作
                      <UpOutlined />
                    </Space>
                  </Button>
                </a>
              </Dropdown>
              <Button htmlType="button" onClick={onReset1} style={{ marginRight: '10px', marginLeft: '220px' }}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
            </div>
          </Form>
        </Drawer>


      </>

      {/* //角色信息 */}
      <>
      
        <Drawer title="角色信息" placement="right" onClose={onCloseone} open={openone} width={500} destroyOnClose>
          <p><CrownOutlined />角色名称：{roleNext.roleName}</p>
          <p><BookOutlined />角色描述：{roleNext.remark}</p>
          <p><ClockCircleOutlined />创建时间：{roleNext.createTime}</p>
          <p><ClockCircleOutlined />修改时间：{roleNext.modifyTime}</p>
          <p> <TrophyOutlined />所拥有的权限:</p>
          <Tree
                checkable
                checkStrictly
                defaultExpandedKeys={nestArr}
                defaultSelectedKeys={nestArr}
                defaultCheckedKeys={nestArr}
                onSelect={onSelect}
                onCheck={onCheck}
                treeData={treeData}
              />
        </Drawer>
      </>
    </div>
  )
}

export default Role